﻿@using SplendidCRM
@using SplendidCRM.Ext
@using SplendidCRM.Ext.Helpers
@using SplendidCRM.Ext.Models
@model CallInboundViewModel

@{
    var formId = Guid.NewGuid();
}



<form id="@formId" class="form" autocomplete="off" data-bind="noSubmit: true">
    @Html.Action("SurveyForm", "ExternalCallSurvey")
    
    <div class="form-header">Basic Info</div>
    <div class="form-section ui-inline-template" data-bind="each: { source: SubcriberBasicInfo }">
        @Html.Field(FieldType.Span, "Phone number", "text: PhoneNumber")
        @Html.Field(FieldType.Span, "Main product", "text: MainProduct")
        @Html.Field(FieldType.Span, "Life Cycle Status", "text: LifeCycleStatus")
        @Html.Field(FieldType.Span, "Active Expiry Date", "text: ActiveExpiryDate")

        @Html.Field(FieldType.Span, "Suspend Expiry Date", "text: SuspendExpiryDate")
        
        @Html.Field(FieldType.Span, "Disable Expiry Date", "text: DisableExpiryDate")
        @Html.Field(FieldType.Span, "Fraud Status", "text: FraudState")
        @Html.Field(FieldType.Span, "First Active Date", "text: FirstActiveDate")

        <div class="clear"></div>
    </div>
    
     <div class="form-header">Balance Info</div>
    <div class="form-section ui-inline-template" data-bind="each: { source: BalanceInfo }">
        @Html.Field(FieldType.Span, "Amount", "text: Amount")
        @Html.Field(FieldType.Span, "Expiration Time", "text: ExpirationTime")
      

        <div class="clear"></div>
    </div>
    
    <div class="form-grid">
        <div class="form-header">Package List / Product List / VAS Service</div>
        <table>
            <thead>
                <tr>
                    <td>Product Name</td>
                    <td>Effective time</td>
                    <td>Rent Cycle Start Time</td>
                    <td>Rent Cycle End Time</td>
                    <td>Rent Status</td>
                </tr>
            </thead>
            <tbody class="ui-inline-template" data-bind="each: { source: ProductList }">
                <script type="text/html">
                    <tr>
                        <td>${data.Name}</td>
                        <td>${format(data.EffectiveTime)}</td>
                        <td>${format(data.RentCycleStartTime)}</td>
                        <td>${format(data.RentCycleEndTime)}</td>
                        <td>${data.RentStatus}</td>
                    </tr>
                </script>
            </tbody>
        </table>
    </div>

    <div class="form-header">Account Info</div>
    <div class="form-section ui-inline-template" data-bind="each: { source: Customer }">
        @Html.Field(FieldType.Span, "ID", "text: ACCOUNT_NUMBER")
        @Html.Field(FieldType.Span, "Phone number", "text: PHONE_OFFICE")
        @Html.Field(FieldType.Text, new { fieldLabel = "Name", containerClass = "solid-border" }, "value: NAME")
        
        @Html.Field(FieldType.Span, "Entered date", "text: DATE_ENTERED")
        @Html.Field(FieldType.Checkbox, "Gender", "checked: GENDER")
        @Html.Field(FieldType.Span, "Modified date", "text: DATE_MODIFIED")
        @Html.Field(FieldType.TextArea, new { fieldClass = "h2x", fieldLabel = "Description", containerClass = "solid-border" }, "value: DESCRIPTION")
        @Html.Field(FieldType.TextArea, new { fieldClass = "h2x", fieldLabel = "Address", containerClass = "solid-border" }, "value: BILLING_ADDRESS_STREET")
        <div class="clear"></div>
    </div>

    <div class="form-header">Call Info</div>
    <div class="form-section ui-inline-template" data-bind="each: { source: Call }">
        @*Html.Field(FieldType.Text, new { fieldLabel = "Subject", containerClass = "solid-border" }, "value: NAME")*@
        @Html.Field(FieldType.Dropdown, "Reason", @"
            options: {
                source: REASONS,
                caption: 'Select reason',
                text: 'x.NAME',
                value: 'x.ID'
            },
            rules: { required: true, messages: { required: 'Please select Reason' } },
            value: REASON_ID")
        @Html.Field(FieldType.Span, "From address", "text: FROM_ADDRESS")
        @Html.Field(FieldType.Dropdown, "Category", @"
            options: {
                source: CATEGORIES,
                caption: 'Select category',
                text: 'x.NAME',
                value: 'x.ID',
                store: 'x.ID'
            },
            rules: { required: true, messages: { required: 'Please select Category' } },
            value: CATEGORY_ID")
        @Html.Field(FieldType.Span, "Start date", "text: DATE_START")
        @Html.Field(FieldType.Dropdown, "Topic", string.Format(@"
            ajax: {{
                url: '{0}',
                async: false,
                active: CATEGORY_ID,
                complete: function() {{
                    this.value = TOPIC_ID.value;
                }},
                data: {{ parentTopicId: CATEGORY_ID.value || util.guidEmpty() }}
            }},
            rules: {{ required: true, messages: {{ required: 'Please select Topic' }} }},
            change: function() {{
                model.TOPIC_ID = this.value;
            }}", Url.Action("GetChildTopics")))
        @Html.Field(FieldType.Text, new { id = "input-case-name", @readonly="readonly", fieldLabel = "Case name", containerClass = "solid-border" }, "value: CASE_NAME")
        @Html.Field(FieldType.TextArea, new { fieldClass = "h2x", fieldLabel = "Description", containerClass = "solid-border" }, "value: DESCRIPTION")        
        
        <div class="form-field form-field-right">
            <div class="form-field-container">
                @Html.Field(FieldType.Hidden, new { id = "input-case-id" }, "value: CASE_ID")
                @Html.Field(FieldType.Button, new { value = "Select", fieldWrapper = false, fieldContainer = false, onclick = "return selectCase()" })
                @Html.Field(FieldType.Button, new { value = "Clear", fieldWrapper = false, fieldContainer = false, onclick = "return clearCase()" })
            </div>
        </div>
        
        @*Html.Field(FieldType.Span, "UCID", "text: UCID")
        @Html.Field(FieldType.Span, "Header number", "text: HEAD_NUMBER")*@
        <div class="clear"></div>
    </div>
    <div class="form-summary" data-valmsg-summary="true">
        <ul></ul>
    </div>
    <div class="form-command">
        <input type="submit" class="form-button" value="Save" href="@Url.Action("Inbound")" data-bind="send: createSaveParams(saveSuccess)" />
        <input type="submit" class="form-button" value="Convert to case" href="@Url.Action("Inbound")" data-bind="send: createSaveParams(convertToCase)" />
        <input type="submit" class="form-button" value="Goto case" data-bind="enabled: !util.guidEmpty(model.Call.CASE_ID), click: gotoCase, klass: { disabled: util.guidEmpty(model.Call.CASE_ID) }"/>
    </div>

    <div class="form-grid">
        <div class="form-header">Unclosed cases</div>
        <table>
            <thead>
                <tr>
                    <td>Case number</td>
                    <td>Name</td>
                    <td>Created date</td>
                    <td>Status</td>
                    <td>Priority</td>
                    <td>Description</td>
                    <td>Action</td>
                </tr>
            </thead>
            <tbody class="ui-inline-template" data-bind="each: { source: UnclosedCases }">
                <script type="text/html">
                    <tr title="${data.NAME}">
                        <td>${data.CASE_NUMBER}</td>
                        <td>
                            <a href="javascript:;" onclick="showCaseDetails('${data.ID}', false, linq.utils.wrap(updateCaseNameForRow).set('mapping', { subject: 'NAME', status: 'STATUS', priority: 'PRIORITY', description: 'DESCRIPTION' }), this);">${data.NAME || '[Blank]'}</a>
                        </td>
                        <td>${format(data.DATE_ENTERED)}</td>
                        <td>${data.STATUS}</td>
                        <td>${getPriorityName(data.PRIORITY)}</td>
                        <td>${data.DESCRIPTION}</td>
                        <td><a href="javascript:;" onclick="internalChangeCase('${data.ID}', $(this).closest('tr').attr('title'), this)">Select case</a></td>
                    </tr>
                </script>
            </tbody>
        </table>
    </div>

    <div class="form-grid">
        <div class="form-header">Call history</div>
        <table>
            <thead>
                <tr>
                    <td>Start date</td>
                    <td>Reason</td>
                    <td>Category</td>
                    <td>Agent</td>
                    <td>Description</td>
                    <td>Related case</td>
                    
                    <td>Action</td>
                </tr>
            </thead>
            <tbody class="ui-inline-template" data-bind="each: { source: CallHistory }">
                <script type="text/html">
                    <tr>
                        <td>${format(data.DATE_START)}</td>
                        <td>${data.REASON_NAME}</td>
                        <td>${data.TOPICS}</td>
                        <td>${data.ASSIGNED_TO_NAME}</td>
                        <td>${data.DESCRIPTION}</td>
                        <td>
                            {{if data.IS_CASE}}
                                <a href="javascript:;" onclick="showCaseDetails('${data.PARENT_ID}', false, linq.utils.wrap(updateCaseNameForRow).set('mapping', { subject: 'PARENT_NAME' }), this);">${data.PARENT_NAME || '[Blank]'}</a>
                            {{else}}
                                &nbsp;
                            {{/if}}
                        </td>
                        <td title="${data.PARENT_NAME}">
                            <a target="_top" href="${'@Url.Action("Inbound", new { callId = "callIdParam" })'.replace(/callIdParam/i, data.ID)}">Edit</a>
                            &nbsp;
                            {{if data.IS_CASE}}
                                <a href="javascript:;" onclick="internalChangeCase('${data.PARENT_ID}', $(this).parent().attr('title'), this)">Select case</a>
                            {{/if}}
                        </td>
                    </tr>
                </script>
            </tbody>
        </table>
    </div>

    <div class="clear"></div>
</form>

<script type="text/javascript">
    function showCaseDetails(id, convertToCase, callback, context) {
        showLightBox(
            'iframe:@Url.Action("CaseDetails", new { id = "idParam", convertToCase = "convertToCaseParam" })'.replace( /idParam/ig , id).replace( /convertToCaseParam/ig , !!convertToCase),
            '1080px',
            '240px',
            function() {
                if (callback) return callback.apply(context || this, arguments);
            });
    }

    
    
    function updateCaseNameForRow(data, mapping) {
        var item = $(this).tmplItem();
        if (mapping) {
            $.each(mapping, function(source, destination) {
                item.data.data[destination] = data[source];
            });
        }

        item.update();
    }
    
    var model = @Html.Raw(Model.Json(true)) ;
    $(function() {
        Globalize.culture('vi');


        model.UnclosedCases = @Html.Raw(Db.Query("exec:[dbo].[GetUnclosedCases]", new { customerId = Model.Customer.ID }).Json(true)) ;


        model.convertToCase = function() {
            showCaseDetails('@Model.Call.Id', true, function(data) {
                if (data) {
                    model.Call.CASE_ID = data.caseId;
                    model.Call.CASE_NAME = data.caseName;
                    linq.model(model).refresh();
                }
            });
        };

        function updateSelectedCase(data) {
            model.Call.CASE_NAME = data.caseName;
            linq.model(model).refresh();
        }

        window.getPriorityName = function(value) {
            return model.PriorityList[value];
        };

        window.internalChangeCase = function(id, name) {
            model.Call.CASE_ID = id;
            model.Call.CASE_NAME = name;
            // refresh form
            linq.model(model).refresh();
            top.scrollTo(0, 200);
        };

        window.selectCase = function() {
            var result = ModulePopup('Cases', 'input-case-id', 'input-case-name', 'account_id=' + model.Call.PARENT_ID, false, null);
            window.ChangeCase = internalChangeCase;
            return result;
        };

        window.clearCase = function() {
            model.Call.CASE_ID = '@Guid.Empty';
            model.Call.CASE_NAME = '';
            linq.model(model).refresh();
        };

        model.gotoCase = function() {
            showCaseDetails(this.Call.CASE_ID, false, updateSelectedCase);
        };

        model.saveSuccess = function(success) {
            alert('Call saved');
        };
        
        model.createSaveParams = function(success) {
            return {
                validate: true,
                stringify: true,
                updated: success,
                data: {
                    redirect: !success,
                    call: this.Call,
                    customer: this.Customer,
                    topic: {
                        topicId: this.Call.TOPIC_ID,
                        categoryId: this.Call.CATEGORY_ID
                    }
                },
                preProcess: function(data) {
                    delete data.call.CATEGORIES;
                    delete data.call.TOPICS;
                    delete data.call.REASONS;
                    data.topic = {
                        categoryId: data.call.CATEGORY_ID,
                        topicId: data.call.TOPIC_ID
                    };
                    delete data.call.CATEGORY_ID;
                    delete data.call.TOPIC_ID;
                    return data;
                }
            };
        };
        linq.model(model, '#@formId');
    });
</script>